package com.smartfast4j.common.component.fileManager.controller;

import com.alibaba.fastjson.JSON;
import com.smartfast4j.common.ThreadManager;
import com.smartfast4j.common.bean.R;
import com.smartfast4j.common.component.fileManager.service.FileService;
import com.smartfast4j.common.component.fileManager.bean.UploadResult;
import com.smartfast4j.common.component.fileManager.service.FileServiceFactory;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.*;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 使用Servlet3.0处理基于plupload上传插件的文件上传
 * 使用@WebServlet配置UploadServlet的访问路径
 * 使用注解@MultipartConfig将一个Servlet标识为支持文件上传
 */
@WebServlet(name="plUploadServlet",urlPatterns="/plUploadServlet")
@MultipartConfig
public class PluploadServlet extends HttpServlet {

    @Value("${fileUpload.tempSavePath}")
    private String uploadPath;

    private static Logger logger = LoggerFactory.getLogger(PluploadServlet.class);

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        Integer chunk = null;// 分割块数
        Integer chunks = null;// 总分割数
        String tempFileName = null;// 临时文件名
        String newFileName = null;// 最后合并后的新文件名
        String uploadType = request.getParameter("uploadType");//上传方式
        FileService fileService;
        if(StringUtils.isNotEmpty(uploadType)){
            //根据用户选择的上传方式获取FileService实例
            fileService = FileServiceFactory.getInstance(uploadType);
        }else {
            //使用默认的FileService实例
            fileService = FileServiceFactory.getDefualInstance();
        }
        //获取上传的文件集合
        Collection<Part> parts = request.getParts();
        for (Part part : parts) {//循环处理上传的文件
            if (part.getName().equals("name")) {
                //获取临时文件名
                tempFileName = request.getParameter("name");
                logger.debug("临时文件名：" + tempFileName);
            } else if (part.getName().equals("chunk")) {
                //获取当前上传的文件块(从0开始算)
                String chunkValue = request.getParameter("chunk");
                chunk = Integer.parseInt(chunkValue);
                logger.debug("当前文件块：" + (chunk + 1));
            } else if (part.getName().equals("chunks")) {
                //文件总分块
                String chunksValue = request.getParameter("chunks");
                chunks = Integer.parseInt(chunksValue);
                logger.debug("文件总分块：" + chunks);
            }else {
                //文件类型
                if (tempFileName != null) {
                    String chunkName = tempFileName;
                    if (chunk != null) {
                        chunkName = chunk + "_" + tempFileName;
                    }
                    InputStream inputStream = part.getInputStream();//获取上传文件输入流
                    saveFile(uploadPath+"/"+chunkName,input2ByteArray(inputStream));
                }
            }
        }
        BufferedOutputStream outputStream = null;
        //文件扩展名
        String extName = tempFileName.substring(tempFileName.lastIndexOf(".") + 1).toLowerCase();
        newFileName = UUID.randomUUID().toString().replace("-", "").concat(".").concat(extName);
        //chunk + 1 == chunks 当前上传的文件块+1等于文件总分块表示已经上传完了，接下来要做的就是合并文件块
        if (chunk != null && chunk + 1 == chunks) {
            outputStream = new BufferedOutputStream(new FileOutputStream(new File(uploadPath, newFileName)));
            // 遍历文件合并
            for (int i = 0; i < chunks; i++) {
                File tempFile = new File(uploadPath, i + "_" + tempFileName);
                byte[] bytes =  FileUtils.readFileToByteArray(tempFile);
                outputStream.write(bytes);
                //outputStream.flush();
                tempFile.delete();//删除临时文件
            }
            outputStream.flush();
            outputStream.close();
            //上传到文件服务器(文件大的时候非常耗时，有待优化)
            UploadResult uploadResult =fileService.uploadFile(uploadPath + "/" + newFileName);
            logger.debug("上传到文件服务器:"+ JSON.toJSONString(uploadResult));
            if(uploadResult.isUploadSuccess()){
                String finalNewFileName = newFileName;
                try {
                    ThreadManager.getInstance().createShortPool().execute(() -> {
                        File localFile = new File(uploadPath, finalNewFileName);
                        localFile.deleteOnExit();//删除本地文件，有bug，删不掉
                    });
                }catch (Exception e){
                    logger.error(e.getMessage(),e);
                }
                write(response, JSON.toJSONString(R.ok(uploadResult)));
                return;
            }else{
                write(response, JSON.toJSONString(R.fail()));
                return;
            }
        }
        Map<String, Object> m = new HashMap<>();
        m.put("status", true);
        m.put("fileUrl", uploadPath + "/" + newFileName);
        write(response, JSON.toJSONString(m));
    }

    /**
     * 将byte数组写入文件
     * @param path
     * @param content
     * @throws IOException
     */
    private void saveFile(String path, byte[] content) throws IOException {
        FileOutputStream fos = new FileOutputStream(path);
        fos.write(content);
        fos.close();
    }

    /**
     * 输入流转字节数组
     * @param inStream
     * @return
     * @throws IOException
     */
    private byte[] input2ByteArray(InputStream inStream)
            throws IOException {
        ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
        byte[] buff = new byte[100];
        int rc = 0;
        while ((rc = inStream.read(buff, 0, 100)) > 0) {
            swapStream.write(buff, 0, rc);
        }
        byte[] in2b = swapStream.toByteArray();
        swapStream.close();
        return in2b;
    }

    /**
     * 根据请求头解析出文件名
     * 请求头的格式：火狐和google浏览器下：form-data; name="file"; filename="snmp4j--api.zip"
     * IE浏览器下：form-data; name="file"; filename="E:\snmp4j--api.zip"
     *
     * @param header 请求头
     * @return 文件名
     */
    public String getFileName(String header) {
        /**
         * String[] tempArr1 = header.split(";");代码执行完之后，在不同的浏览器下，tempArr1数组里面的内容稍有区别
         * 火狐或者google浏览器下：tempArr1={form-data,name="file",filename="snmp4j--api.zip"}
         * IE浏览器下：tempArr1={form-data,name="file",filename="E:\snmp4j--api.zip"}
         */
        String[] tempArr1 = header.split(";");
        /**
         *火狐或者google浏览器下：tempArr2={filename,"snmp4j--api.zip"}
         *IE浏览器下：tempArr2={filename,"E:\snmp4j--api.zip"}
         */
        String[] tempArr2 = tempArr1[2].split("=");
        //获取文件名，兼容各种浏览器的写法
        String fileName = tempArr2[1].substring(tempArr2[1].lastIndexOf("\\") + 1).replaceAll("\"", "");
        return fileName;
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        this.doGet(request, response);
    }

    private void write(HttpServletResponse response, String str) throws IOException {
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        out.println(str);
        out.flush();
        out.close();
    }

    @Override
    public void init(ServletConfig config) throws ServletException {
        File up = new File(uploadPath);
        if (!up.exists()) {
            up.mkdir();
        }
    }
}